package com.zls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zls.mapper.TbusersMapper;
import com.zls.pojo.Tbusers;
import com.zls.service.TbusersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TbusersServiceImpl extends ServiceImpl<TbusersMapper, Tbusers> implements UserDetailsService, TbusersService {
    @Autowired
    private TbusersMapper tbusersMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //连接数据库
        //条件查询
        LambdaQueryWrapper<Tbusers> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Tbusers::getUsername,username);
        Tbusers tbusers = tbusersMapper.selectOne(lambdaQueryWrapper);
        if (tbusers!=null){
            //需要去数据库查询 角色  权限等数据
            // GrantedAuthority  代表角色和权限
            List<GrantedAuthority> list=new ArrayList<>();
            if ("zhangsan".equals(tbusers.getUsername())){
                //凡是角色 必须添加  ROLE_
                list.add(new SimpleGrantedAuthority("ROLE_student"));
                list.add(new SimpleGrantedAuthority("ROLE_admin"));
            }else if ("com.zls".equals(tbusers.getUsername())){
                list.add(new SimpleGrantedAuthority("update"));//凡是不是ROLE开头的就是权限
            }else {
                list.add(new SimpleGrantedAuthority("ROLE_teacher"));
            }
            return new User(username,tbusers.getPassword(),list);
        }
        System.out.println("用户名不存在");
        return null;
    }
}
